package binance.controller
import binance.model.*

class SellController {
    def register = {
        def buys = Buy.currentInvestments(session.user)
        return [buys : buys]
    }

    def details = {
        try {
            def buy = Buy.findByIdAndUser(params['buy'],session.user)
            if (buy)
            return [buy : buy]
        }catch(Exception e) {
            render(text:"")
        }
    }

    def edit = {
        def sell = Sell.findById(params['id'])
        if (sell.buy.user.id != session.user.id) {
            render("Incorrect user ${sell.buy.user.id} == ${session.user.id}")
            return
        }

        return [sell : sell]
    }

    def save = {
        params['price'] = Utils.correctNumber(params['price'])
        params['count'] = Utils.correctNumber(params['count'])
        params['target'] = Utils.correctNumber(params['target'])

        def buy = Buy.findByIdAndUser(params['buy'],session.user)
        def sell = new Sell(buy:buy,price:params['price'],count:params['count'])
        if (sell.save())
            render(text:"Successfully registered $sell")
        else
            render(text:"Error while registering $sell")
    }

    def update = {
        params['price'] = Utils.correctNumber(params['price'])
        params['count'] = Utils.correctNumber(params['count'])
        params['target'] = Utils.correctNumber(params['target'])
        
        def sell = Sell.findById(params['id'])
        if (sell.buy.user.id != session.user.id) {
            render("Incorrect user ${sell.buy.user.id} == ${session.user.id}")
            return
        }
        sell.count = new Integer(params['count'])
        sell.price = new Double(params['price'])
        sell.save()
        redirect(controller:"page",action:"start")
    }

    def delete = {
        def sell = Sell.findById(params['id'])
        if (sell.buy.user.id == session.user.id) {
            sell.delete()
            render(text:"")
        }else{
            log.debug "${sell.buy.user} = ${session.user}"
            render(text:"incorrect user")
        }
    }
}
